package com.bingxu.flink.timer;

import com.bingxu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author :BingXu
 * @description :TODO
 * @date :2021/8/17 20:09
 * @modifier :
 */

public class ProcessReplaceTimer {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 10086);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        // 设置水印自动抛出的时间周期
        env.getConfig().setAutoWatermarkInterval(1000);

        // 当水位达到10的时候，发出黄色预警
        env
                .socketTextStream("localhost", 9999)
                .map((MapFunction<String, WaterSensor>) value -> {
                    String[] fields = value.split(",");
                    return new WaterSensor(fields[0], Long.parseLong(fields[1]) * 1000, Integer.valueOf(fields[2]));
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    // 变量是每一个SubTask共享，对同一个process的所有元素而言
                    private long time;
                    private int cnt = 0;

                    /**
                     * 设置定时器，定时器为处理时间5S后触发，5S触发后进行相应的操作处理
                     * 定时器当水位首次超过10时，5s预警-->黄色预警 水位超过20 且 已经有过预警 3S预警--> 红色预警
                     * @param value 传入元素的值
                     * @param ctx 上下文对象
                     * @param out 输出处理对象
                     * @throws Exception
                     */
                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {

                        if (value.getVc() > 10 && cnt==0) {
                            cnt++;
                            time = ctx.timerService().currentProcessingTime() + 8000;
                            ctx.timerService().registerProcessingTimeTimer(time);
                        } else if (value.getVc() > 20 || (cnt > 0 && value.getVc() > 10)) {
                            ctx.timerService().deleteProcessingTimeTimer(time);
                            time = ctx.timerService().currentProcessingTime() + 1000;
                            ctx.timerService().registerProcessingTimeTimer(time);
                        } else {
                            // 只要不是连续超过10以上，就可以不预警
                            cnt=0;
                            ctx.timerService().deleteProcessingTimeTimer(time);
                        }
                        out.collect(value.toString());
                    }

                    /**
                     * 处理定时器触发的操作
                     * @param timestamp 定时器的时间
                     * @param ctx 上下文对象
                     * @param out 输出对象
                     * @throws Exception
                     */
                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        System.out.println("timestamp = " + timestamp);
                        out.collect("处理定时器 开始预警了");
                    }
                }).print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
